package org.tong.jpa.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.tong.jpa.repo.StudentJpaRepo;
import org.tong.jpa.repo.StudentRepoImpl;
import org.tong.jpa.entities.Student;
import org.tong.jpa.service.inter.StudentService;

import javax.transaction.Transactional;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

@Service
@Transactional
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentRepoImpl studentRepo;

    @Autowired
    private StudentJpaRepo studentJpaRepo;

    @Override
    public Student findById(Long id) {
        return studentRepo.findStudentById(id);
    }

    @Override
    public void deleteById(Long id) {
        studentJpaRepo.deleteById(id);
    }

    @Override
    public void update(Student student) {
        Assert.notNull(student.getId(), "更新时对象主键不能为空");
        studentJpaRepo.save(student);
    }

    @Override
    public Long save(Student student) {
        studentJpaRepo.save(student);
        return student.getId();
    }

    @Override
    public Student saveAndFind(Student student) {
        save(student);
        return studentJpaRepo.findById(student.getId()).get();
    }

    @Override
    public List<Student> findAll() {
        return studentJpaRepo.findAll();
    }

    @Override
    public void saveAll(Student... students) {
        Arrays.stream(students).forEach(student -> {
            studentJpaRepo.save(student);
        });
    }
}
